--[[


   Save file format
Line			Value
---------------------
1				Money
2				Shield
3				Armor
4				Energy
5				Position X
6				Position Y
7				Party
8				Ship
9				Weapon table
10				Inventory


]]

firsttime=initArray2(32,true)

-- Seriously what the crap does this function do??
-- Remember, readability above speed..
function unique(t)
	local r = {}
	local i = nil
	local n = 0
	for k,v in pairs(t) do
		if v~="" then
			r[#r+1] = v
		end
		i=v
	end
	return r
end

function string.split(t, b)
	local cmd = {}
	local match = "[^%s]+"
	if b then
		match = "%w+"
	end
	if type(b) == "string" then match = "[^"..b.."]+" end
	if not t then return invalid() end
	for word in string.gmatch(t, match) do
		table.insert(cmd, tonumber(word))
	end
	return cmd
end

function table.msg(t)
	local str=""
	for _,v in ipairs(t) do
		if (str=="") then
			str=str..v
		else
			str=str..","..v
		end
	end
	return str
end

function dataset(id,dn,d)
	local dd=tonumber(d)
	if (dn==1) then
		credits[id]=dd
	elseif (dn==2) then
		shield[id]=dd
	elseif (dn==3) then
		armor[id]=dd
	elseif (dn==4) then
		energy[id]=dd
	elseif (dn==5) then
		pos[id][1]=dd
	elseif (dn==6) then
		pos[id][2]=dd
	elseif (dn==7) then
		inParty[id][2]=dd
	elseif (dn==8) then
		shipt[id]=dd
	elseif (dn==9) then
		cwslots[id]=string.split(d,",")
	elseif (dn==10) then
		invslot[id]=string.split(d,",")
	end
end

function datanull(id)
	credits[id]=2000
	armor[id]=100
	shield[id]=100
	energy[id]=500
	pos[id]=spawnPos
	inParty[id]={false,0}
	shipt[id]=1
	cwslots[id]={1,0,0,0,0,0,0,0,0}
	invslot[id]={0,0,0}
	firsttime[id]=true
end

-- returns a string representation of a table
function table_str(t)
	local s = ""
	
	local function ret(t)
		s = s .. "{"
		for key,value in pairs(t) do
			s = s .. key ..": "
			if type(value) == "table" then
				ret(value)
			else
				s = s .. tostring(value)
			end
			s = s ..","
		end
		s = s .. "}"
	end
	
	ret(t)
	return s
	
end

function datasave(id)
	local usgn=player(id,"usgn")
	if usgn > 0 then		
		os.execute('touch "/home/engi/public_rpg/sys/lua/space_rpg/savedata/'..usgn..'.sav"')
		--os.execute('chmod 666 "/home/engi/public_rpg/sys/lua/space_rpg/savedata/'..usgn..'.sav"')
		--local m = assert(io.open('sys/lua/space_rpg/savedata/'..usgn..'.sav','w'))
		--m:write(credits[id].."\n"..shield[id].."\n"..armor[id].."\n"..energy[id].."\n"..pos[id].x.."\n"..pos[id].y.."\n"..inParty[id][2].."\n"..shipt[id].."\n"..table.msg(cwslots[id]).."\n"..table.msg(invslot[id]))
		--m:close()
		--msg2(id,"Data save completed successfully!")
		
		local player = {credits = credits[id],
			shield = shield[id],
			armor = armor[id],
			energy = energy[id],
			pos_x = pos[id].x,
			pos_y = pos[id].y,
			in_party = inParty[id],
			shipt = shipt[id],
			weapon_table = cwslots[id],
			inv_table = invslot[id]
		}
		
		pickle.dump(player,'sys/lua/space_rpg/savedata/'..usgn..'.sav')		
	else
		msg2(id,"Data save failed - not logged into USGN!")
	end
end

function dataread(id)
	local usgn = player(id,"usgn")
	if usgn > 0 then
	
		local m = assert(io.open('sys/lua/space_rpg/savedata/'..usgn..'.sav','r'))
		if m then 
			-- file exists.. now load it
			local player = pickle.load('sys/lua/space_rpg/savedata/'..usgn..'.sav')
			credits[id] = player.credits
			armor[id] = player.armor
			energy[id] = player.energy
			pos[id].x = player.pos_x
			pos[id].y = player.pos_y
			local buf = table_str(player.in_party)
			inParty[id] = player.in_party
			
			
			msg2(id,buf)
			cwslots[id] = player.weapon_table
			invslot[id] = player.inv_table
			msg2(id,"Data load completed successfully for usgn user: "..usgn.."!")
		else -- file doesnt exist, load first timer data
			datanull(id)
			msg2(id,"Welcome for the first time, user: "..usgn.."!")
		end	
		
	else
		msg2(id,"Data load failed - not logged into USGN!")
	end
end



addhook("join","player_load")
function player_load(id)
	dataread(id)
end

addhook("leave","player_save")
function player_save(id)
	datasave(id)
	datanull(id)
end